LoadLibrary <- function() {
  FAILMESSAGE<-list()
  lib <- c("Rpdb","bio3d","ggplot2","compiler","parallel","rlecuyer","snow","modeltools","flexclust","MASS","stringr","rgl","ellipse","BioPhysConnectoR","grid","gridExtra","tcltk","lattice","reshape2","plyr","scales","colorspace","bio3d")
  for (i in 1:length(lib)) {
    E<-lib[i]
    if(!(paste0("package:",E,sep="") %in% search())){
      if(!require(E,character.only=T)){
        if(!isTRUE(install.packages(E))){
          print(paste("Please install the package per 'R CMD INSTALL':",E))
          FAILMESSAGE[[i]]<-paste("Please install the package per 'R CMD INSTALL':",E)
        }
      }
    } 
  }
  print("Error Summary of library: ...") 
  if(!(length(FAILMESSAGE)==0)){
    cat((paste("-",unlist(FAILMESSAGE),collapse="\n")))}else{cat("     None")}
} 

LoadSource<-function(){
  vec<-c("iGEM_Calc.R","iGEM_clustalo.R","iGEM_StatFunc.R","iGEM_Plot.R","iGEM_StatFunc.R","iGEM_ReducingAlphabet")
  for (i in 1:length(vec)){
    if (!exists(as.character(paste0("Spec_",vec[i],sep="",collapse=NULL),mode="function"))){
      source(as.character(vec[i]))
    }  
  }
}

library(tcltk)

LoadLibrary()

##Clustalo implementation##
MSA_File<-function(clustalo=T) {#ONLY MSA
  #print("Set working directory:")
  #setwd(tk_choose.dir())
  print("Count of data expected (integer):")
  E<-readline() #Number of Files
  print("Now choose sequence files being already blasted")
  if(is.integer(as.integer(E))) {#load files
    #Select Data Path
    Path<-NULL
    Name<-NULL
    subDir<-NULL
    for (i in 1:E){
      Path[i]<-tk_choose.files() 
      Name[i]<-basename(Path[i])  #with extension
      subDir[i]<-sub("^([^.]*).*", "\\1", Name[i]) #without extension      
    }
    for (i in 1:E){      
      Name<-subDir[i]
      get.Blast<-BioPhysConnector::read.fasta(Path[i])
      if(!mod){
        try(get.MSA<-MSA_Seq(get.Blast,clustalo,clustalw2))
      }
      else{
        get.Blast<-Name[i]
        try(get.MSA<-MSA_Seq(get.Blast,clustalo))
      }
      try(bio3d::write.fasta(alignment=get.MSA,file=paste(Name,"_aln.fasta")) )
    }
  }
  else{
    print("Error: No integer was submitted. Stopping program.")
  }          
  return(invisible())
}

MSA_Seq<-function(files="",clustalo=F){  
  if (clustalo){      
      try(files<-clustalo(files,detectCores(),mod=T))      
    }
  return(files)
}

###Sequence Analysis##

Analyse_Start <- function(MI.Treshold=0.9,MI.Tresh.Norm=c("Z","Norm"),method.MI1="ORMI",method.MI2="SUMI",gap.char="-",nullmod=100){ #Secondary Starting Option: Analyze different sets of data in one step
  if (length(MI.Tresh.Norm)>1){MI.Tresh.Norm<-MI.Tresh.Norm}
  Count.Threshold=1
  cat("Set working directory: \n")
  setwd(tk_choose.dir())
  cat("Choose Amino Acid Alphabet to use: \n")
  cat(" - Norm: Normal Alphabet without Reduction \n")
  cat(" - CSI/CSII/CS_SR: Chemical Structure Reduction Alphabet \n")
  cat(" etc...")
  Check<-F
  udData.Alph<-unique(dData.Alph) #unique Set of Alphabet instead (F.EX) NORM NORM NORM ... CSI CSI CSI .... etc....
  while (!Check){    
    Alph<-readline()
    if (any(grepl(Alph,udData.Alph$Alph))&&!(is.numeric(Alph))){
      Check<-T
      cat(paste("You have chosen'",Alph,"'. \n"))
    }else{ 
      cat("Error: Choose an existing Alphabet. Now choose again. \n")
    }
  }
  cat("Count of data expected (integer): \n")
  E<-readline() #Number of Files
  cat("Now choose files \n") 
  if(is.integer(as.integer(E))){
    #Select Data Path
    Path<-NULL
    Name<-NULL
    subDir<-NULL
    OrDir <- getwd()
    for (i in 1:E){
      Path[i]<-tk_choose.files() 
      Name[i]<-basename(Path[i])#with extension
      cat(paste("\n You have chosen:",Name[i]))
      #here create ordner in WD like WD/Data/... <- in Data files of Data
      #subDir without extension equals Name
      subDir[i]<-sub("^([^.]*).*", "\\1", Name[i]) 
      #create directory corresponding to name of givn File
      subName<-paste(subDir[i],"-A_",Alph,sep="",collapse=NULL)
      dir.create(file.path(OrDir,subName), showWarnings = FALSE)
    } 
    for (i in 1:E){ 
      #Set WD corresponding to each starting dataset: now inside rigth directory
      subName<-paste(subDir[i],"-A_",Alph,sep="",collapse=NULL)
      setwd(file.path(OrDir,subName))#always set directory to origin
      #Process each data vector
      Data<-LoadData_mod(Path[i])#load data of csv or fasta
      #got list of two vector of id and seqs
      #TA_mod(Data,Name) TOTAL ANALZYATION
      TA_mod(Data,subDir[i],Alph,Count.Threshold,MI.Treshold,MI.Tresh.Norm,method.MI1,method.MI2,gap.char,nullmod)
    }
  }
  else{
    cat("Error: No integer was submitted. Stopping program.")
  }
}

LoadData_mod <- function(Path) {
  E<-NULL 
  Name<-basename(Path)
  #Distinction between CSV (vectorized data in one column) or fasta (read each second line or read with read.fasta [last option is implemented])
  if (grepl("csv",Name)){
    E<-read.csv(Path,header=FALSE) #from list to vector
    E<-as.vector(as.matrix(E))
    E<-unique(E)
    id<-NULL
  }else{
    Fasta<-BioPhysConnectoR::read.fasta(Path,to.upper=T) #[1,]
    Ali<-Fasta$ali #Is data.frame
    #sequence of MSA got all the same length
    Ali<-unique(Fasta$ali) #get unique sets of alignment -> f.ex. HIV DV has more than 100 double sets
    id<-rownames(Ali)
    E<-my.con_apply(Ali,length(Ali),length(id))
  } 
  DF.Data<-data.frame("ali"=E)
  rownames(DF.Data)<-id
  return(DF.Data)    
}

TA_mod <- function(Data,Name,Alph,Count.Threshold,MI.Treshold=0.9,MI.Tresh.Norm=c("Z","Norm"),method.MI1="ORMI",method.MI2="SUMI",gap.char="-",nullmod=10000) { #Analyze one set  corresponding to TotalAnalyzation of MI.R
  Len<-nchar(as.character(Data[1,1]))
  id<-rownames(Data) 
  E<-apply(Data,1,RA3,alphabet=Alph)    
  Data<-data.frame("ali"=as.vector(E))  
  rownames(Data)<-id 
  if (Count.Treshold==1){
    OrDiTAr<-getwd()
    dir.create(file.path(getwd(),'N1'), showWarnings = FALSE)
    setwd(file.path(getwd(),'N1'))
    Normal_mod(Data,Name,Alph,MI.Treshold,MI.Tresh.Norm,method.MI1,method.MI2,gap.char,nullmod) 
    setwd(OrDiTAr)
  }  
  cat("Finished calculation.")
} 

General<-function(Data,Name,Alph="Norm",NormMod=F){#with bio3d package sequence orientated
  colnames(Data)<-seq(1,ncol(Data),1)
  rownames(Data)<-seq(1,nrow(Data),1)
  OrDir<-getwd()
  dir.create(file.path(getwd(),'General'), showWarnings = FALSE)
  
  Name<-paste(Name,"-A_",Alph,sep="",collapse=NULL)
  
  setwd(file.path(OrDir,'General')) 
  if(NormMod&&(Alph=="Norm")){
    bio3d_conservative(Data,Name)
    bio3d_consensus_Seq(Data,Name)
  }
  SH_Ent<-BioPhysConnectoR::get.entropy(Data)
  Save2D_Vec(as.vector(SH_Ent),Name,x_set="",lab=c("Residue","SH Entropy [bit]")) 
  setwd<-OrDir
}
Normal_mod <- function(Data.Vec,Name,Alph,MI.Treshold=0.9,MI.Tresh.Norm=c("Z","Norm"),method.MI1="ORMI",method.MI2="SUMI",gap.char="-",nullmod=10000) {
  id<-rownames(Data.Vec)
  Data.Vec<-as.vector(Data.Vec[,1])
  cat(paste("Data:",Name,"using",Alph,"\n"))
  Matrix <- VecToMat(Data.Vec,Sep=TRUE) 
  Name<-paste(Name,"_N1-1",sep="")
  
  cat("Starting normal calculation. \n")
  Analyze_Set(Matrix,Name,id,Alph,T,MI.Treshold,MI.Tresh.Norm,method.MI1,method.MI2,gap.char,nullmod)
}

VecToMat <- function(Data,Sep=FALSE) { #Matrix: complete vecorized or each char seperated
  E <- NULL
  if (Sep) {
    for (i in 1:length(Data)) {
      j <- NULL
      j <- substring(Data[i], seq(1,nchar(Data[i]),1), seq(1,nchar(Data[i]),1))                                                                            
      E <- rbind(E,j)       
    }     
  }
  else {
    for (i in 1:length(Data)) {
      E <- rbind(E,Data[i])  
    } 
  }
  rownames(E) <- seq(1,NROW(E),1)
  return(E)
}

Analyze_Set <- function(Matrix,Name,id,Alph,NormMod,MI.Treshold=0.9,MI.Tresh.Norm=c("Z","Norm"),method.MI1="ORMI",method.MI2="SUMI",gap.char="-",nullmod=10000) { #Sequence Matrix of
  OrDirSet<-getwd()
  # Safe Complete Table/Matrix of all possible sets via Normal and N
  rownames(Matrix)<-id 
  FileNamePre<-paste(Name,"_complete.csv",sep="")
  write.table(Matrix,file=FileNamePre,append=FALSE,quote=FALSE,sep=" ", na="NA",dec=".",row.names=TRUE,col.names=TRUE)
  General(Matrix,Name,Alph,NormMod)
  setwd(OrDirSet)
  # Save All matrix in Picture and
  Name<-paste0(Name,"-A_",Alph,sep="",collapse=NULL)
  AnalyzeMI(Matrix,Name,"","","",MI.Treshold,MI.Tresh.Norm,method.MI1,method.MI2,gap.char,nullmod) 
  setwd(OrDirSet)
}

AnalyzeMI <- function(Matrix,Name,x_set="",y_set="",lab=c(),MI.Treshold=0.9,MI.Tresh.Norm=c("Z","Norm"),method.MI1="ORMI",method.MI2="SUMI",gap.char="-",nullmod=10000){##x,y_set lab(c())
  f_get.mie<-function(Matrix,method = method.MI, gap.char=gap.char,nullmod=10000){
    MIE<-BioPhysConnectoR::get.mie(aln=Matrix,method = method, gapchar=gap.char,nullmod=nullmod)    
    return(MIE)
  }
  mean_MI<-function(MI,COLS){
    LEN<-length(MI[[1]][1]) 
    mi<-0
    nullmodel<-0
    nullsq<-0
    nullvar<-0
    for (i in 1:LEN){
      mi<-mi+as.vector(unlist(MI[[i]][1]))
      nullmodel<-nullmodel+as.vector(unlist(MI[[i]][2]))
      nullsq<-nullsq+as.vector(unlist(MI[[i]][3]))
      nullvar<-nullvar+as.vector(unlist(MI[[i]][4]))        
    }
    mi<-matrix(mi/LEN,ncol=COLS)
    nullmodel<-matrix(nullmodel/LEN,ncol=COLS)
    nullsq<-matrix(nullsq/LEN,ncol=COLS)
    nullvar<-matrix(nullvar/LEN,ncol=COLS)
    MI<-NULL
    MI$mi<-mi
    MI$nullmodel<-nullmodel
    MI$nullsq<-nullsq
    MI$nullvar<-nullvar
    return(MI)
  }
  
  OrDir<-getwd()
  dir.create(file.path(getwd(),'MI'), showWarnings = FALSE) 
  setwd(file.path(getwd(),'MI')) 
  lab<-c("Amino Acid Residue","MI [bit]")
  #Calculation
  mi<-c("_mi","_mi-null","_mi-nullsq","_mi-nullvar") 
  mi2<-c("_mi2","_mi2-null","_mi2-nullsq","_mi2-nullvar") 
  
  LOCAL<-NULL
  for(i in 1:parallel::detectCores()){
    LOCAL<-append(LOCAL,"localhost")
  }
  COLS<-ncol(Matrix)  
  
  cl <- makeCluster(as.vector(LOCAL),type = "SOCK")
  clusterSetupRNG(cl)
  MI.raw<-clusterCall(cl, f_get.mie,Matrix,method.MI1,gap.char,nullmod)  
  MI<-mean_MI(MI.raw,COLS)
  MI.raw=NULL
  stopCluster(cl)
  
  cl <- makeCluster(as.vector(LOCAL),type = "SOCK")
  clusterSetupRNG(cl)
  MI.raw<-clusterCall(cl, f_get.mie,Matrix,method.MI2,gap.char,nullmod)  
  MI2<-mean_MI(MI.raw,COLS)
  MI.raw=NULL
  stopCluster(cl)   
  
  DF<-data.frame(MI=as.vector(MI$mi),MI2=as.vector(MI2$mi))
  gg_mi<-ggplot(DF,aes(x=MI,y=MI2))+geom_point()+xlab("MI [bit]")+ylab("MI2 [bit]")+theme_bw()
  FileName<-paste(Name,"MI-MI2",sep="-")
  ggsave(filename=paste(FileName,"against.png",sep="-"),plot=gg_mi,dpi=330,width=8,height=5.21) 
  DF<-data.frame(MI=as.vector(MI$nullmodel),MI2=as.vector(MI2$nullmodel))
  gg_mi<-ggplot(DF,aes(x=MI,y=MI2))+geom_point()+xlab("MI [bit]")+ylab("MI2 [bit]")+theme_bw()
  FileName<-paste(Name,"MInull-MI2null",sep="-")
  ggsave(filename=paste(FileName,"against.png",sep="-"),plot=gg_mi,dpi=330,width=8,height=5.21) 
  
  VecMat<-NULL 
  for (i in 1:4){
    #Normal MI
    FileNamePre<-paste(Name,mi[i],sep="")
    SaveMI(MI[[i]],FileNamePre,x_set,y_set,lab,MI.Treshold,MI.Tresh.Norm)
    FileNamePre<-paste(Name,mi2[i],sep="")
    SaveMI(MI2[[i]],FileNamePre,x_set,y_set,lab,MI.Treshold,MI.Tresh.Norm)
    #Vectorized diag MI into VecMat 
    VecMat <- rbind(VecMat,diag(MI[[i]]),diag(MI2[[i]]))
  }	
  #getting vectorized matrix (matrix(i,i)) and save it
  rownames(VecMat)<-c("mi","mi2","mi_null","mi2_null","mi_nullsquare","mi2_nullsquare","mi_nullvar","mi2_nullvar") 
  FileNamePre<-paste(Name,"_mi-vectorized","_",".csv",sep="")
  write.table(VecMat,file=FileNamePre,append=FALSE,quote=FALSE,sep=" ", na="NA",dec=".",row.names=TRUE,col.names=TRUE)
  #getting Pplot of mi,mi2,mi_null,mi2_null 
  for (i in 0:1){
    FileNamePre<-paste(Name,"",mi[i+1],"diag",sep="")
    Save2D_Vec(as.vector(VecMat[((2*i)+1),]),FileNamePre,x_set,lab) 
    FileNamePre<-paste(Name,"",mi2[i+1],"diag",sep="")
    Save2D_Vec(as.vector(VecMat[((2*i+1)+1),]),FileNamePre,x_set,lab)  
    FileNamePre<-paste(Name,paste(mi[i+1],mi2[i+1],sep="-"),"_together",sep="") 
    DF<-as.data.frame(cbind(VecMat[((2*i)+1),],VecMat[((2*i+1)+1),])) 
    COLNN<-c("Normal","NULL")
    colnames(DF)<-c("MI","MI2")
    Save2D_DF(DF,FileNamePre,x_set,lab)    
    gg_together<-ggplot(data=DF,aes(x=MI,y=MI2))+geom_point()+xlab("MI [bit]")+ylab("MI2 [bit]")+theme_bw()
    ggsave(filename=paste(Name,COLNN[i],"against.png",sep="-"),plot=gg_together,dpi=330,width=8,height=5.21) 
  }
  setwd<-OrDir
}

SaveMI <- function(Matrix,Name,x_set="",y_set="",lab=c(),MI.Treshold=0.9,MI.Tresh.Norm="Z"){ 
  FileName<-paste(Name,".csv",sep="")
  write.table(Matrix,file=as.character(FileName),append=FALSE,quote=FALSE,sep=" ", na="NA",dec=".",row.names=TRUE,col.names=TRUE) 
  SaveVolc(Matrix,Name,x_set,y_set,lab) 
  SaveHeat(Matrix,Name,x_set,y_set,"p75") 
  SaveContactMI(Matrix,Name,MI.Treshold,MI.Tresh.Norm)
} 
SaveContactMI<-function(Matrix,Name,MI.Treshold=0.9,MI.Tresh.Norm="Z"){
  fContact<-function(x,MI.Treshold,Max){
    if(is.numeric(x)&&(x>=(MI.Treshold*Max))){
      return(1)
    }else{
      return(0)
    }
  }
  fNorm<-function(x,max){
    return(x/max)
  }
  if(MI.Tresh.Norm=="Z"){
    Mean<-mean(Matrix)
    SD<-sd(Matrix)
    Matrix<-apply(Matrix,c(1,2),z_score_2,Mean=Mean,SD=SD)
  }
  if(MI.Tresh.Norm=="Norm"){
    Max=max(Matrix)
    Matrix<-apply(Matrix,c(1,2),fNorm,Max=Max)
  } 
  Max<-max(Matrix)
  Matrix<-apply(Matrix,c(1,2),fContact,MI.Treshold=MI.Treshold,Max=Max)
  FileName<-paste(Name,"_MIcontact.csv",sep="")
  write.table(Matrix,file=as.character(FileName),append=FALSE,quote=FALSE,sep=" ", na="NA",dec=".",row.names=TRUE,col.names=TRUE)  
}

my.con_apply <- function(Ali,lAli,lid) {  
  E<-NULL
  for (j in 1:lid){
    Sub.app<-NULL
    for (i in 1:(lAli/lid)){
      Sub.app<-paste(Sub.app,Ali[j,][i],sep="",collapse=NULL)
    }
    E[j]<-Sub.app
  }
  E<-as.vector(E)
  return(E)
}

###ANM Analysis###
igem_NMA<-function(pdb=NULL,List.pdbs=NULL,ids=NULL,name,modes.count=c(7,12),Weight=F,Weight.num=1,v.parallel=F){
  #Sys.chmod(getwd(), mode = "0777", use_umask = TRUE)
  #Sys.umask(mode = NA)
  if(isTRUE(v.parallel)){NCORE<-detectCores()}else{NCORE<-1}
  
  if(!is.null(pdb)){
    gaps.pos <- gap.inspect(pdb$xyz)
    if(isTRUE(Weight)){
      gaps.pos <- gap.inspect(pdb$xyz)
      wts<-igem_make.weights(pdb$xyz[,gaps.pos$f.inds])^Weight.num
      #gaps.res <- gap.inspect(pdbs$ali)
    }else{wts<-NULL}    
    
    modes.calpha<-bio3d::nma(pdb,ff="calpha",fc.weights=wts)
    modes.anm<-bio3d::nma(pdb,ff="anm",fc.weights=wts)
    modes.pfanm<-bio3d::nma(pdb,ff="pfanm",fc.weights=wts)
    modes.reach<-bio3d::nma(pdb,ff="reach",fc.weights=wts)
    modes.sdenm<-bio3d::nma(pdb,ff="sdenm",fc.weights=wts)
    List.modes<-list(modes.calpha,modes.anm,modes.pfanm,modes.reach,modes.sdenm)
    Vec.modes<-c("calpha","anm","pfanm","reach","sdenm")
    
    pdf(file=paste0(name,"_modes.pdf",sep="",collapse=NULL))
    print({
      plot(modes.calpha)
      mtext(paste0("ff: ",Vec.modes[1]),side=1,line=4)
      plot(modes.anm)
      mtext(paste0("ff: ",Vec.modes[2]),side=1,line=4)
      plot(modes.pfanm)
      mtext(paste0("ff: ",Vec.modes[3]),side=1,line=4)
      plot(modes.reach)
      mtext(paste0("ff: ",Vec.modes[4]),side=1,line=4)
      plot(modes.sdenm)
      mtext(paste0("ff: ",Vec.modes[5]),side=1,line=4)
    })
    dev.off()
    igem_RMSIP(modes.1=modes.calpha,modes.2=modes.anm,Name=paste0(name,"_calpha-anm"),lab=c("anm","calpha"))
    igem_RMSIP(modes.1=modes.calpha,modes.2=modes.pfanm,Name=paste0(name,"_calpha-pfanm"),lab=c("pfanm","calpha"))
    igem_RMSIP(modes.1=modes.calpha,modes.2=modes.reach,Name=paste0(name,"_calpha-reach"),lab=c("reach","calpha"))
    igem_RMSIP(modes.1=modes.calpha,modes.2=modes.sdenm,Name=paste0(name,"_calpha-sdenm"),lab=c("sdenm","calpha"))
    
    igem_RMSIP(modes.1=modes.anm,modes.2=modes.pfanm,Name=paste0(name,"_anm-pfanm"),lab=c("pfanm","anm"))
    igem_RMSIP(modes.1=modes.anm,modes.2=modes.reach,Name=paste0(name,"_anm-reach"),lab=c("reach","anm"))
    igem_RMSIP(modes.1=modes.anm,modes.2=modes.sdenm,Name=paste0(name,"_anm-sdenm"),lab=c("sdnem","anm"))
    
    igem_RMSIP(modes.1=modes.pfanm,modes.2=modes.reach,Name=paste0(name,"_pfanm-reach"),lab=c("reach","pfanm"))
    igem_RMSIP(modes.1=modes.pfanm,modes.2=modes.sdenm,Name=paste0(name,"_pfanm-sdenm"),lab=c("sdenm","pfanm"))   
    igem_RMSIP(modes.1=modes.reach,modes.2=modes.sdenm,Name=paste0(name,"_reach-sdenm"),lab=c("sdenm","reach"))
    
    for (i in modes.count[1]:modes.count[2]){
      bio3d::mktrj.nma(modes.calpha,mode=i,file=paste0(name,"_nma_mode-calpha-",i,".pdb",sep="",collapse=NULL))  
      bio3d::view.modes(modes.calpha,mode=i,outprefix=paste0(name,"_nma_mode-calpha-",i,sep="",collapse=NULL)  )
      
      bio3d::mktrj.nma(modes.anm,mode=i,file=paste0(name,"_nma_mode-anm-",i,".pdb",sep="",collapse=NULL))
      bio3d::view.modes(modes.anm,mode=i,outprefix=paste0(name,"_nma_mode-anm-",i,sep="",collapse=NULL))
      bio3d::mktrj.nma(modes.pfanm,mode=i,file=paste0(name,"_nma_mode-pfanm-",i,".pdb",sep="",collapse=NULL))
      bio3d::view.modes(modes.pfanm,mode=i,outprefix=paste0(name,"_nma_mode-pfanm-",i,sep="",collapse=NULL))
      bio3d::mktrj.nma(modes.reach,mode=i,file=paste0(name,"_nma_mode-reach-",i,".pdb",sep="",collapse=NULL))
      bio3d::view.modes(modes.reach,mode=i,outprefix=paste0(name,"_nma_mode-reach-",i,sep="",collapse=NULL))
      bio3d::mktrj.nma(modes.sdenm,mode=i,file=paste0(name,"_nma_mode-sdenm-",i,".pdb",sep="",collapse=NULL))
      bio3d::view.modes(modes.sdenm,mode=i,outprefix=paste0(name,"_nma_mode-sdenm-",i,sep="",collapse=NULL))
      
      for (j in 1:length(List.modes)){
        cm<-bio3d::dccm(List.modes[[j]])      
        png(filename = paste0(name,"_nma-",as.character(Vec.modes[j]),"-",i,".png",sep="",collapse=NULL), width = 1500, height = 780)
        print({plot(cm, sse = pdb, contour = F, col.regions = bwr.colors(20), at = seq(-1,  1, 0.1))})      
        dev.off()  
        bio3d::view.dccm(cm,pdb,outprefix=paste0(name,"_nma_dccm-",as.character(Vec.modes[j]),"-",i,sep="",collapse=NULL))
      }
      
    }
    i<-1
    for (i in 1:length(Vec.modes)){
      defe<-bio3d::deformation.nma(List.modes[[i]])
      defsums<-rowSums(defe$ei[,1:3])
      flucts<-bio3d::fluct.nma(List.modes[[i]],mode.inds=seq(modes.count[1],modes.count[2]))
      bio3d::write.pdb(pdb=NULL,xyz=List.modes[[i]]$xyz,file=paste0(name,"_",as.character(Vec.modes[i]),"_deform.pdb"),b=defsums)
      bio3d::write.pdb(pdb=NULL,xyz=List.modes[[i]]$xyz,file=paste0(name,"_",as.character(Vec.modes[i]),"_fluct.pdb"),b=flucts)   
    }
  }
  
  if(!is.null(List.pdbs)&&!is.null(ids)){
    
    pdbs<-get.pdbs(List.pdbs)
    #as alignment -< pdbs
    SeqId<-seqidentity(pdbs) 
    SUM<-matrix(as.vector(summary(SeqId)),ncol=length(ids))
    colnames(SUM)<-ids
    write.csv(SUM,file=paste0(name,"_sum_seqid_pdbs.txt",sep="",collapse=NULL))
    gaps.pos <- gap.inspect(pdbs$xyz)
    if(isTRUE(Weight)){
      gaps.pos <- gap.inspect(pdbs$xyz)
      wts<-igem_make.weights(pdbs$xyz[,gaps.pos$f.inds])^Weight.num
      #gaps.res <- gap.inspect(pdbs$ali)
    }else{wts<-NULL}
    
    try(modes.calpha<-bio3d::nma.pdbs(pdbs,ff="calpha", rm.gaps = T,full=T,fit=T,fc.weights=wts,ncore=NCORE,nseq.scale=NCORE))
    try(modes.anm<-bio3d::nma.pdbs(pdbs,ff="anm", rm.gaps = T,full=T,fc.weights=wts,ncore=NCORE,nseq.scale=NCORE))
    try(modes.pfanm<-bio3d::nma.pdbs(pdbs,ff="pfanm", full=T,rm.gaps = T,fc.weights=wts,ncore=NCORE,nseq.scale=NCORE))
    try(modes.reach<-bio3d::nma.pdbs(pdbs,ff="reach",full=T, rm.gaps = T,fc.weights=wts,ncore=NCORE,nseq.scale=NCORE))
    #try(modes.sdenm<-bio3d::nma.pdbs(pdbs,ff="sdenm",full=T, rm.gaps = T,fc.weights=wts,ncore=NCORE,nseq.scale=NCORE))
    #sdenm cant be calculated
    Vec.modes<-c("calpha","anm","pfanm","reach")#,"sdenm")
    
    #plot modes 
    pdf(file=paste0(name,"_ensemble-modes-fluct.pdf",sep="",collapse=NULL))
    print({
      plot(modes.calpha,main=Vec.modes[1])
      legend("topleft", legend = ids, col = seq(1, nrow(modes.calpha$fluctuations)), lty = 1)
      mtext(paste0("ff: ",Vec.modes[1]),side=1,line=4)
      plot(modes.anm,main=Vec.modes[2])
      legend("topleft", legend = ids, col = seq(1, nrow(modes.anm$fluctuations)), lty = 1)
      mtext(paste0("ff: ",Vec.modes[2]),side=1,line=4)
      plot(modes.pfanm,main=Vec.modes[3])
      legend("topleft", legend = ids, col = seq(1, nrow(modes.pfanm$fluctuations)), lty = 1)
      mtext(paste0("ff: ",Vec.modes[3]),side=1,line=4)
      plot(modes.reach,main=Vec.modes[4])
      legend("topleft", legend = ids, col = seq(1, nrow(modes.reach$fluctuations)), lty = 1)
      mtext(paste0("ff: ",Vec.modes[4]),side=1,line=4)
      #plot(modes.sdenm,main=Vec.modes[5])
      #  legend("topleft", legend = ids, col = seq(1, nrow(modes$fluctuations)), lty = 1)
      #mtext(paste0("ff: ",Vec.modes[5]),side=1,line=4)
    })
    dev.off()
    #
    
    List.modes<-list(modes.calpha,modes.anm,modes.pfanm,modes.reach)#,modes.sdenm)
    #   Vec.modes<-c("calpha","anm","pfanm","reach","sdenm")
    
    gaps.res <- gap.inspect(pdbs$ali)
    gaps.pos <- gap.inspect(pdbs$xyz)
    
    cm<-list()
    cm.all<-list()
    
    for (i in 1:length(Vec.modes)){
      RMSIP<-rmsip(List.modes[[i]]$U.subs[,,1], List.modes[[i]]$U.subs[,,2] )
      png(filename = paste0(name,"_enma_rmsip-",as.character(Vec.modes[i]),".png",sep="",collapse=NULL), width = 1500, height = 780)
      print(plot(RMSIP,main=paste0(name,"enma_rmsip-",Vec.modes[i],sep="",collapse=NULL),xlab="RMSIP a","RMSIP b"))      
      dev.off()  
      
      
      write.csv(List.modes[[i]]$frequencies,file=paste0(name,"_mode-freq_",as.character(Vec.modes[i]),".csv",sep="",collapse=NULL))
      
      cij<-bio3d::dccm(List.modes[[i]],ncore=NCORE,nseq.scale=NCORE)    
      cm[[i]]<-cij
      dimnames(cij$all.dccm)<-list(NULL,NULL,ids)
      png(filename = paste0(name,"_enma-CrosCorr-",as.character(Vec.modes[i]),".png",sep="",collapse=NULL), width = 1500, height = 780)
      print(plot.dccm(cij$all.dccm))      
      dev.off()  
      
      cij.all<-bio3d::dccm.mean(cij$all.dccm,cutoff.sims=length(ids),cutoff.cij=0,ncore=NCORE,nseq.scale=NCORE)
      cm.all[[i]]<-cij.all
      png(filename = paste0(name,"_enma_all-CrosCorr-",as.character(Vec.modes[i]),".png",sep="",collapse=NULL), width = 1500, height = 780)
      print(plot.dccm(cij.all, main = "Consensus Residue Cross Correlation") )     
      dev.off()  
      
      png(filename = paste0(name,"_ensemble_nma-HeatRMSIP-",as.character(Vec.modes[i]),".png",sep="",collapse=NULL), width = 1500, height = 780)
      print({
        heatmap((1 - List.modes[[i]]$rmsip), labRow =NULL, labCol = ids, symm = TRUE)
      })      
      dev.off()        
      
      rmsd.map <- rmsd(pdbs$xyz, a.inds = gaps.pos$f.inds, fit = TRUE,ncore=NCORE)
      png(filename = paste0(name,"_ensemble_nma-HeatRMSD-",as.character(Vec.modes[i]),".png",sep="",collapse=NULL), width = 1500, height = 780)
      print({
        print(heatmap(rmsd.map, labRow = NULL, labCol = ids, symm = TRUE,main=paste0(name,"ENMA-HeatRMSD-",as.character(Vec.modes[i]),sep="",collapse=NULL))) 
      })      
      dev.off() 
    }    
  }  
  return(list(cm,cm.all,List.modes))
}  
